import { reqUserChannels, reqAllChannels, reqUpdatedChannel } from '@/api/index'
const state = {
  userChannels: [],
  allChannels: []
}

const actions = {
  // 获得用户的频道
  async getUserChannels ({ commit }) {
    const res = await reqUserChannels()
    if (res.status === 200) {
      commit('GETUSERCHANNELS', res.data.data.channels)
    }
  },
  // 获得全部的频道
  async getAllChannels ({ commit }) {
    const res = await reqAllChannels()
    if (res.status === 200) {
      commit('GETALLCHANNELS', res.data.data.channels)
    }
  },
  // 更新频道，请求接口
  async updatedChannels () {
    // newArr是浅拷贝，里面的对象还是原来的对象，操作的时候会把userChannels的名字都删除了
    // const newArr = state.userChannels.filter((item) => { return item.id !== 0 })
    // newArr.forEach((obj, index) => {
    //   delete obj.name
    //   obj.seq = index
    // })
    // 需要使用map,重新开辟空间
    const newArr = state.userChannels.filter((item) => { return item.id !== 0 })
    const thenewArr = newArr.map((obj, index) => {
      const newobj = { ...obj }
      // 深拷贝
      delete newobj.name
      newobj.seq = index
      return newobj
    })
    // thenewArr是深拷贝
    try {
      await reqUpdatedChannel(thenewArr)
    } catch (error) {
      console.log(error.message)
    }
  },
  // 添加频道
  addChannels ({ commit, dispatch }, obj) {
    commit('ADDCHANNEL', obj)
    dispatch('updatedChannels')
  },
  // 删除频道
  removeChannels ({ commit, dispatch }, obj) {
    commit('REMOVECHANNELS', obj)
    dispatch('updatedChannels')
  }
}
const mutations = {
  GETUSERCHANNELS (state, data) {
    console.log('mut', 2)
    state.userChannels = data
  },
  GETALLCHANNELS (sate, data) {
    sate.allChannels = data
  },
  ADDCHANNEL (state, obj) {
    state.userChannels.push(obj)
  },
  REMOVECHANNELS (state, obj) {
    const index = state.userChannels.findIndex((item) => item.id === obj.id)
    state.userChannels.splice(index, 1)
  }

}

const getters = {
  otherChannels (state) {
    // 怎么判断一个数组里面是否含有某个对象，并且将两个数组里面相同的对象去掉
    const otherChannels = []
    state.allChannels.forEach((item) => {
      const i = JSON.stringify(state.userChannels).indexOf(JSON.stringify(item))
      if (i === -1) {
        otherChannels.push(item)
      }
    })
    return otherChannels
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
